<?php

namespace xing\bytedance;

use xing\contentSafe\core\BaseSafe;
use xing\contentSafe\core\ImageSafeInterFace;
use xing\helper\resource\HttpHelper;

class BytedanceBase
{

    private $domain = 'https://developer.toutiao.com/';

    public $cacheType = 'Yii';
    public $cache;
    public $appId;
    public $secret;
    public $targets = ['porn', 'disgusting', 'politics'];

    public static function init($appId, $secret)
    {
        $class = new static;
        $class->appId = $appId;
        $class->secret = $secret;
        return $class;
    }

    public function getAccessToken($reCache = false)
    {
        $cacheKey = 'TouTiaoAccessToken';
        if (!empty($this->cacheType)) {
            $accessToken = $this->getCache($cacheKey);
            if (!empty($accessToken)) return $accessToken;
        }
        $params = ['appid' => $this->appId, 'secret' => $this->secret, 'grant_type' => 'client_credential'];
        $result = HttpHelper::post($this->domain . 'api/apps/v2/token', json_encode($params),  ['Content-Type: application/json']);
        $data = json_decode($result)->data;
        if (empty($data->access_token ?? null)) throw new \Exception('请求accessToken失败, 返回值:' . $result);
        if (!empty($this->cache)) $this->setCache($cacheKey, $data->access_token, $data->expires_in - 1000);
        return $data->access_token;
    }

    public function getCacheDrive()
    {
        if ($this->cacheType == 'Yii') {
            return \Yii::$app->cache;
        } else {
            return $this->cache;
        }
    }

    public function getCache($cacheKey)
    {
        return $this->getCacheDrive()->get($cacheKey);
    }

    public function setCache($cacheKey, $value, $time = null)
    {
        return $this->getCacheDrive()->set($cacheKey, $value, $time);
    }

    /**
     * 解密
     * @param $encryptedData
     * @param $iv
     * @param $sessionKey
     * @return mixed
     * @throws \Exception
     */
    public function decryptData($encryptedData, $iv, $sessionKey)
    {
        if (strlen($sessionKey) != 24) throw new \Exception('非法', -41001);
        $aesKey = base64_decode($sessionKey);

        if (strlen($iv) != 24) throw new \Exception('非法', -410020);
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode( $result );
        if( $dataObj  == NULL ) throw new \Exception('aes 解密失败', -41003);
        return $dataObj;
    }
}
